package coolq

import (
	"encoding/json"
	"fmt"
	"io/ioutil"

	log "github.com/sirupsen/logrus"

	"github.com/Mrs4s/MiraiGo/message"
	"github.com/Mrs4s/go-cqhttp/lib"
	"github.com/robfig/cron/v3"
)

type TopUrlNews struct {
	Code    int    `json:"code"`
	Data    Data   `json:"data"`
	Message string `json:"message"`
}
type Calendar struct {
	LYear   int    `json:"lYear"`
	LMonth  int    `json:"lMonth"`
	LDay    int    `json:"lDay"`
	Animal  string `json:"animal"`
	YearCn  string `json:"yearCn"`
	MonthCn string `json:"monthCn"`
	DayCn   string `json:"dayCn"`
	CYear   int    `json:"cYear"`
	CMonth  int    `json:"cMonth"`
	CDay    int    `json:"cDay"`
	GzYear  string `json:"gzYear"`
	GzMonth string `json:"gzMonth"`
	GzDay   string `json:"gzDay"`
	IsToday bool   `json:"isToday"`
	IsLeap  bool   `json:"isLeap"`
	NWeek   int    `json:"nWeek"`
	NcWeek  string `json:"ncWeek"`
	IsTerm  bool   `json:"isTerm"`
	Term    string `json:"term"`
}
type HistoryList struct {
	Event string `json:"event"`
}
type NewsList struct {
	Title    string `json:"title"`
	URL      string `json:"url"`
	Category string `json:"category"`
}
type Phrase struct {
	Phrase  string `json:"phrase"`
	Explain string `json:"explain"`
	From    string `json:"from"`
	Example string `json:"example"`
	Simple  string `json:"simple"`
	Pinyin  string `json:"pinyin"`
}
type Sentence struct {
	Wrong    bool   `json:"wrong"`
	Author   string `json:"author"`
	Sentence string `json:"sentence"`
}
type Poem struct {
	Content []string `json:"content"`
	Type    string   `json:"type"`
	Title   string   `json:"title"`
	Author  string   `json:"author"`
}
type Detail struct {
	Date                string `json:"date"`
	TextDay             string `json:"text_day"`
	CodeDay             string `json:"code_day"`
	TextNight           string `json:"text_night"`
	CodeNight           string `json:"code_night"`
	High                string `json:"high"`
	Low                 string `json:"low"`
	Rainfall            string `json:"rainfall"`
	Precip              string `json:"precip"`
	WindDirection       string `json:"wind_direction"`
	WindDirectionDegree string `json:"wind_direction_degree"`
	WindSpeed           string `json:"wind_speed"`
	WindScale           string `json:"wind_scale"`
	Humidity            string `json:"humidity"`
}
type Weather struct {
	City      string `json:"city"`
	WeatherOf string `json:"weatherOf"`
	Detail    Detail `json:"detail"`
}
type Data struct {
	Intro       string        `json:"_intro"`
	Calendar    Calendar      `json:"calendar"`
	HistoryList []HistoryList `json:"historyList"`
	NewsList    []NewsList    `json:"newsList"`
	Phrase      Phrase        `json:"phrase"`
	Sentence    Sentence      `json:"sentence"`
	Poem        Poem          `json:"poem"`
	Weather     Weather       `json:"weather"`
}

func (bot *CQBot) cronGroupMessage() {
	GroupCode := int64(318195769)
	var ele []message.IMessageElement
	data, err := getTopNewsData()
	if err != nil {
		ele = make([]message.IMessageElement, 0)
		ele = append(ele, message.NewText("news not found:"+err.Error()))
	} else if data.Code == 200 {
		d := data.Data.Calendar
		date := fmt.Sprintf("%d年%d月%d日 (农历%s%s) %s \n\n", d.CYear, d.CMonth, d.CDay, d.MonthCn, d.DayCn, d.NcWeek)
		newsList := " 【今日简报】 \n "
		for _, v := range data.Data.NewsList {
			newsList += fmt.Sprintf("[%s] %s \n", v.Category, v.Title)
		}
		historyList := " 【历史上的今天】 \n "
		for _, v := range data.Data.HistoryList {
			historyList += v.Event + "\n"
		}
		sentence := fmt.Sprintf("\n 【每日一句】 \n %s --- %s ", data.Data.Sentence.Sentence, data.Data.Sentence.Author)
		str := date + newsList + historyList + sentence
		ele = append(ele, message.NewText(str))
	}
	bot.SendGroupMessage(GroupCode, &message.SendingMessage{
		Elements: ele,
	})
}

func getTopNewsData() (t *TopUrlNews, err error) {
	resp, err := lib.HttpGet("https://news.topurl.cn/api")
	if err != nil {
		return
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	json.Unmarshal(body, &t)
	return
}

func CronNews(bot *CQBot) {
	log.Info("cron start...")
	c := cron.New()
	d, err := c.AddFunc("0 9 * * *", bot.cronGroupMessage)
	if err == nil {
		log.Info("cron start success! cron id :", d)
	}
	c.Start()
}
